import {
	Button,
	Collapse,
	Form,
	Input,
	Row,
	Col,
	TreeSelect,
	message,
	Select,
} from 'antd'
import React, {useEffect, useState} from 'react'
import {history, connect} from 'umi'
import styles from '@/assets/common/css/page.less'
import {
	addRoleApply,
	editRoleApply,
	examineRoleApply,
	viewRoleApply,
} from '@/service/system/roleApplication'
import {translateDataToTree} from '@/utils/common'
import {getCompany} from '@/service/common'

const {TextArea} = Input
const {Panel} = Collapse
const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const add = (props: any) => {
	const {query} = props.location
	const [type, setType] = useState<string>()
	const [companyData, setCompanyData] = useState([]) // 所属组织
	const [form] = Form.useForm()
	const [examineForm] = Form.useForm()
	const [detailedData, setDetailedData] = useState<any>({})
	const [examineType, setExamineType] = useState<boolean>(false)

	/** 获取用户所属公司数据 */
	const onCompany = () => {
		getCompany().then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setCompanyData(list as any)
			}
		})
	}
	useEffect(() => {
		onCompany()
	}, [])

	useEffect(() => {
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else if (hrefs.includes('edit')) {
			setType('edit')
		} else if (hrefs.includes('add')) {
			setType('add')
			form.setFieldsValue({orgId: props?.user?.orgId})
		} else if (hrefs.includes('copy')) {
			setType('copy')
		} else {
			setType('examine')
		}
	}, [])
	useEffect(() => {
		if (query?.id) {
			viewRoleApply({id: query?.id}).then((res: any) => {
				if (res?.success) {
					setDetailedData(res?.data)
					if (
						res?.data?.approvalStatus === 2 ||
						res?.data?.approvalStatus === 3
					) {
						setExamineType(true)
					}
					form.setFieldsValue({
						...res?.data,
						applyUser:
							res?.data?.approvalStatus === 0
								? ''
								: res?.data?.applyUser,
					})
					examineForm.setFieldsValue({
						approvalOpinion: res?.data?.approvalOpinion,
					})
				}
			})
		}
	}, [query])
	// 表单提交
	const onFinish = async (btnType: string) => {
		const fromData = await form.validateFields()
		const data = {
			...fromData,
			approvalStatus: btnType === 'save' ? 0 : 1,
		}
		if (query?.id && type === 'edit') {
			editRoleApply({...data, id: query?.id})
				.then((res: any) => {
					if (res?.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		} else {
			// 新增角色申请
			addRoleApply(data)
				.then((res: any) => {
					if (res?.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}
	}
	// 审批
	const onExamine = async (btnType: string) => {
		const fromData = await examineForm.validateFields()
		const data = {
			...fromData,
			id: query?.id,
			roleCode: detailedData?.roleCode,
			roleName: detailedData?.roleName,
			roleNameZh: detailedData?.roleNameZh,
			approvalStatus: btnType === 'agree' ? 2 : 3,
		}
		examineRoleApply(data)
			.then((res: any) => {
				if (res?.success) {
					message.success(res.msg)
					history.goBack()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}
	const customizeHeader = (value: string) => (
		<div>
			<div className={styles.tip} />
			{value}
		</div>
	)
	return (
		<div className={styles.page}>
			<div className={`${styles.content} ${styles.formDetils}`}>
				<Collapse
					defaultActiveKey={['1', '2']}
					ghost
					expandIconPosition="end"
					collapsible="header">
					<Panel header={customizeHeader('基础信息')} key="1">
						<Form
							name="basic"
							form={form}
							layout="horizontal"
							labelCol={{style: {width: 120}}}
							disabled={type === 'view' || type === 'examine'}
							autoComplete="off">
							<Row gutter={12}>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="角色编码"
										name="roleCode"
										rules={[
											{
												required: true,
											},
											{
												pattern: /^[A-Za-z]+$/,
												message:
													'角色编码只允许输入英文',
											},
										]}>
										<Input
											placeholder="请输入"
											maxLength={30}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="角色名称"
										name="roleName"
										rules={[
											{
												required: true,
												message: '请输入角色名称',
											},
										]}>
										<Input
											placeholder="请输入"
											maxLength={30}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="角色所在组织"
										name="merchantId"
										rules={[{required: true}]}>
										<TreeSelect
											showSearch
											style={{width: '100%'}}
											dropdownStyle={{
												maxHeight: 400,
												overflow: 'auto',
											}}
											placeholder="请选择"
											allowClear
											treeDefaultExpandAll
											fieldNames={fieldNames}
											treeNodeFilterProp="name"
											treeDataSimpleMode
											treeData={companyData}
										/>
									</Form.Item>
								</Col>
								{type === 'edit' || type === 'examine' ? (
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="状态"
											name="approvalStatus">
											<Select
												disabled
												options={[
													{
														value: 0,
														label: '待审核',
													},
													{
														value: 1,
														label: '审核中',
													},
													{
														value: 2,
														label: '审核通过',
													},
													{
														value: 3,
														label: '审核拒绝',
													},
												]}
											/>
										</Form.Item>
									</Col>
								) : (
									''
								)}

								{type === 'view' || type === 'examine' ? (
									<>
										<Col
											sm={{span: 24}}
											md={{span: 12}}
											lg={{span: 8}}>
											<Form.Item
												label="提交审核人"
												name="applyUser">
												<Input
													placeholder="-"
													disabled
												/>
											</Form.Item>
										</Col>
										<Col
											sm={{span: 24}}
											md={{span: 12}}
											lg={{span: 8}}>
											<Form.Item
												label="提交审核时间"
												name="applyTime">
												<Input
													placeholder="-"
													disabled
												/>
											</Form.Item>
										</Col>
									</>
								) : (
									''
								)}
								{type === 'view' ? (
									<>
										<Col
											sm={{span: 24}}
											md={{span: 12}}
											lg={{span: 8}}>
											<Form.Item
												label="审批人"
												name="approvalUser">
												<Input
													placeholder="-"
													disabled
												/>
											</Form.Item>
										</Col>
										<Col
											sm={{span: 24}}
											md={{span: 12}}
											lg={{span: 8}}>
											<Form.Item
												label="审批时间"
												name="approvalTime">
												<Input
													placeholder="-"
													disabled
												/>
											</Form.Item>
										</Col>
									</>
								) : (
									''
								)}
								<Col span={24}>
									<Form.Item
										label="描述"
										name="roleNameZh"
										rules={[
											{
												required: true,
											},
										]}>
										<TextArea
											placeholder="请输入（最多500个字）"
											autoSize={{minRows: 4, maxRows: 6}}
											maxLength={500}
										/>
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</Panel>
					{type === 'examine' || (type === 'view' && examineType) ? (
						<Panel header={customizeHeader('审批意见')} key="2">
							<Form
								name="basic"
								form={examineForm}
								layout="horizontal"
								labelCol={{style: {width: 120}}}
								disabled={type === 'view'}
								autoComplete="off">
								<Row gutter={12}>
									<Col span={24}>
										<Form.Item
											label="描述"
											name="approvalOpinion"
											rules={[
												{
													required: true,
												},
											]}>
											<TextArea
												placeholder="请给出审批意见（最多200个字）"
												autoSize={{
													minRows: 4,
													maxRows: 6,
												}}
												maxLength={200}
											/>
										</Form.Item>
									</Col>
								</Row>
							</Form>
						</Panel>
					) : (
						''
					)}
				</Collapse>
				<div className={styles.wrap}>
					{type === 'add' || type === 'edit' || type === 'copy' ? (
						<>
							<Button
								type="primary"
								htmlType="submit"
								onClick={() => onFinish('save')}>
								保存
							</Button>
							<Button
								type="primary"
								htmlType="submit"
								onClick={() => onFinish('submit')}>
								提交
							</Button>
						</>
					) : null}
					{type === 'examine' ? (
						<>
							<Button
								type="primary"
								htmlType="submit"
								onClick={() => onExamine('agree')}>
								同意
							</Button>
							<Button
								type="primary"
								htmlType="submit"
								onClick={() => onExamine('refuse')}>
								拒绝
							</Button>
						</>
					) : null}
					<Button
						htmlType="reset"
						className="reset"
						onClick={() => {
							history.goBack()
						}}>
						{type === 'view' ? '返回' : '取消'}
					</Button>
				</div>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(add)
